package org.lzuploader.gui.listeners.servers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.lzuploader.gui.WServers;
import org.lzuploader.model.Config;

/** This class is used when we want to delete a server from the config.
 * 
 * @author Emmanuel Cron
 *
 */
public class RemoveSelectionListener implements SelectionListener
{
    /** The logger for this class. */
    private static Log log = LogFactory.getLog(RemoveSelectionListener.class);
    
    /** Used when the widget is selected by default.
     * @param e The associated event
     */
    @Override
    public void widgetDefaultSelected(final SelectionEvent e)
    {
        widgetSelected(e);
    }

    /** Used when the user clicked on the widget.
     * @param e The associated event
     */
    @Override
    public void widgetSelected(final SelectionEvent e)
    {
        log.debug("User clicked on remove server button.");
        
        log.trace("Fetching data.");
        
        final Config config = Config.getInstance();
        
        Shell wServersShell = null;
        for (int i = 0 ; i < e.display.getShells().length ; i++)
        {
            if (e.display.getShells()[i].getData() instanceof WServers)
            {
                wServersShell = e.display.getShells()[i];
                break;
            }
        }
        
        final WServers servers = (WServers) wServersShell.getData();
        final List list = servers.getList();
        final int currentSelection = list.getSelectionIndex();
        
        if (currentSelection >= 0)
        {
            final String name = servers.getList().getSelection()[0];
            
            config.getServers().remove(name);
            config.save();
            servers.resetComponents();
        }
    }

}
